﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using WpfApp1.Model;
using WpfApp1.ViewModel;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        static string datasoruce = Directory.GetCurrentDirectory() + @"\desktop_tools.sqlite";
        public static SQLiteConnection connection = new SQLiteConnection("Data Source=" + datasoruce);
        MainViewModel MainViewModel;

        public MainWindow()
        {
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
            InitializeComponent();
            MainViewModel = new MainViewModel()
            {
                Loginfo = "",
                Version = "桌面管理工具 v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
            };
            show.DataContext = MainViewModel;
            Show_Init_Right_Info();
            // 初始化数据库
            Init_rules_table();
            Init_log_table();
            ScheduleNotice();
            InputData input = new InputData();
        }

        private void Init_rules_table()
        {
            if (connection.State != System.Data.ConnectionState.Open)
            {
                connection.Open();
                if (!File.Exists(datasoruce))
                {
                    SQLiteConnection.CreateFile(datasoruce);
                }
                string createsql = "create table if not exists rules(id INTEGER PRIMARY KEY AUTOINCREMENT,prefix nvarchar(128),directorypath nvarchar(255))";
                SQLiteCommand command = new SQLiteCommand(createsql, connection);
                command.ExecuteNonQuery();
            }
        }

        private void Init_log_table()
        {
            string sql = "create table if not exists logs(id INTEGER PRIMARY KEY AUTOINCREMENT,info nvarchar(512),source nvarchar(32),created_at INTEGER)";
            SQLiteCommand command = new SQLiteCommand(sql, connection);
            int res = command.ExecuteNonQuery();
            string sql_new = "select *  from logs";
            SQLiteCommand command1 = new SQLiteCommand(sql_new, connection);
            SQLiteDataReader reader = command1.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine("{0} {1} {2}", reader["id"], reader["info"], reader["created_at"]);
            }
        }

        private void Show_Init_Right_Info()
        {
            string usage = "使用方法：\n\n规则设置：  点击后进行设置文件整理的规则，需要先设置前缀，然后再设置路径。\n前缀格式> xxx_ （以英文下划线结尾）。\n\n开始整理：  点击后会按照设置的规则将桌面上的文件进行按目录移动。\n\n    祝使用愉快！";
            MainViewModel.Usage = usage;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            Ruleslist list = new Ruleslist();

            list.ShowDialog();
        }

        // 开始整理按钮
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            string sql = "select id,prefix,directorypath from rules";
            SQLiteCommand command = new SQLiteCommand(sql, connection);
            SQLiteDataReader reader = command.ExecuteReader();
            Dictionary<string, string> map = new Dictionary<string, string>();
            List<string> prefixlist = new List<string>();
            while (reader.Read())
            {
                prefixlist.Add(reader["prefix"].ToString());
                map.Add(reader["prefix"].ToString(), reader["directorypath"].ToString());
            }

            show.DataContext = MainViewModel;
            show.Children.Remove(info);
            TextBox text = new TextBox()
            {
                Name = "logshow",
                Text = "fgdfg",
                //Width = 370,
                TextWrapping = TextWrapping.Wrap
            };

            Binding binding = new Binding()
            {
                Source = MainViewModel,
                Path = new PropertyPath("Loginfo"),
            };

            text.SetBinding(TextBox.TextProperty, binding);
            int elementcout = show.Children.Count;
            for (int i = 0; i < elementcout; i++)
            {
                show.Children.RemoveAt(i);
            }

            show.Children.Add(text);

            // 查找文件
            RulesViewModel rulesViewModel = new RulesViewModel();
            string sourceDir = rulesViewModel.Dict_select;
            if (sourceDir == null)
            {
                Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            }

            DirectoryInfo directory = new DirectoryInfo(sourceDir);
            foreach (FileInfo file in directory.GetFiles())
            {
                string filename = file.Name;
                string[] filenameArr = filename.Split("_".ToCharArray());
                string pre = filenameArr[0];

                string keyPre = pre + "_";
                if (map.ContainsKey(keyPre))
                {
                    string destpath = map[keyPre];
                    if (destpath == "")
                    {
                        continue;
                    }

                    DirectoryInfo destdirectoryInfo = new DirectoryInfo(destpath);
                    if (!destdirectoryInfo.Exists)
                    {
                        MessageBox.Show(" 目录：" + destpath + " 不存在");
                        MainViewModel.Loginfo += "目录：" + destpath + " ==> 不存在\n";
                        continue;
                    }

                    string destfile = destpath.TrimEnd(@"\/".ToCharArray()) + @"\" + filename;
                    try
                    {
                        (new Tools()).MoveFile(sourceDir + @"\" + filename, destfile);
                        string loginfo = filename + " ==> 已经处理完毕\n";
                        MainViewModel.Loginfo += loginfo;
                        Log(loginfo, "move_file");
                    }
                    catch (ArgumentNullException err)
                    {
                        MessageBox.Show(err.Message);
                        Log(err.Message, "move_file");
                        continue;
                    }
                    catch (InvalidDataException err)
                    {
                        MainViewModel.Loginfo += "\n" + err.Message;
                        Log(err.Message, "move_file");
                        continue;
                    }
                    catch (OperationCanceledException err)
                    {
                        MainViewModel.Loginfo += "\n" + err.Message;
                        Log(err.Message, "move_file");
                        return;
                    }

                }
                else
                {
                    continue;
                }
            }

            MainViewModel.Loginfo += "\n处理完毕!\n";
            MessageBox.Show("处理完毕");
        }

        private int Log(string info, string from)
        {
            TimeSpan now = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string nowsec = now.TotalSeconds.ToString();
            string sql = "insert into logs (info,source,created_at) values (\"" + info + "\",\"" + from + "\"," + nowsec + ")";
            SQLiteCommand command = new SQLiteCommand(sql, connection);
            return command.ExecuteNonQuery();
        }

        private void CloseWindow(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (connection.State == System.Data.ConnectionState.Open)
            {
                connection.Close();
            }

        }

        private void CloseWindow(object sender, EventArgs e)
        {
            if (connection.State == System.Data.ConnectionState.Open)
            {
                connection.Close();
            }
        }

        // 日志记录
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            string sql = "select * from logs order by created_at desc limit 100 ";
            SQLiteCommand command = new SQLiteCommand(sql, connection);
            SQLiteDataReader reader = command.ExecuteReader();

            ListView list = new ListView()
            {
                Name = "loglist",
            };

            GridView gridView = new GridView();
            list.View = gridView;
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "信息",
                DisplayMemberBinding = new Binding("Info"),
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "来源",
                DisplayMemberBinding = new Binding("Source")
            });
            gridView.Columns.Add(new GridViewColumn()
            {
                Header = "时间",
                DisplayMemberBinding = new Binding("Create_time")
            });

            while (reader.Read())
            {
                list.Items.Add(new LogsViewModel(new Log()
                {
                    Id = (long)reader["id"],
                    Info = reader["info"].ToString().Trim("\n".ToCharArray()),
                    Source = reader["source"].ToString(),
                    Create_time = (long)reader["created_at"]
                }));

            }

            if (show.Children.Count == 1)
            {
                show.Children.RemoveAt(0);
            }

            show.Children.Remove(info);

            show.Children.Add(list);
        }

        // 展示帮助内容
        private void ViewHelp(object sender, RoutedEventArgs e)
        {

            int elementnum = show.Children.Count;

            for (int i = 0; i < elementnum; i++)
            {
                show.Children.RemoveAt(i);
            }

            string help_text = "使用方法：\n\n规则设置：  点击后进行设置文件整理的规则，需要先设置前缀，然后再设置路径。\n前缀格式> xxx_ （以英文下划线结尾）。\n\n开始整理：  点击后会按照设置的规则将桌面上的文件进行按目录移动。\n\n" +
                "日程提醒：   点击后设置好主题、提前提醒天数跟日期（注意日期格式 xxxx-xx-xx），系统会这个日期的前x天在打开工具时进行提示（当前仅支持这种方式，以后看需求定）。\n\n" +
                "注：本工具中的列表项只要在单元格内回车就可以开始新条目。" +
                "\n\n    祝使用愉快！（来自桌面小工具开发团队【标配1人】）";
            TextBlock text = new TextBlock()
            {
                Text = help_text,
                FontSize = 12,
                FontFamily = new FontFamily("simkai"),
                TextWrapping = TextWrapping.Wrap,
                Background = Brushes.LightGoldenrodYellow
            };

            show.Children.Add(text);
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            View.Schedule schedule = new View.Schedule
            {
                WindowStartupLocation = WindowStartupLocation.CenterScreen
            };
            schedule.ShowDialog();
        }

        private void ScheduleNotice()
        {
            ScheduleViewModel.InitDb();
            try
            {
                string sql_notice = "select title,time,pre_intervals from schedules;";
                SQLiteCommand command = new SQLiteCommand(sql_notice, connection);
                SQLiteDataReader reader = command.ExecuteReader();
                string notices = "";
                int num = 0;
                while (reader.Read())
                {
                    string time = reader["time"].ToString();
                    DateTime date = DateTime.Parse(time);
                    DateTime startTime = date.AddDays((-(long)reader["pre_intervals"]));
                    DateTime now = DateTime.Now;
                    if (DateTime.Compare(now, startTime) < 0 || DateTime.Compare(now, date) > 0)
                    {
                        continue;
                    }

                    if (num == 0)
                    {
                        notices += "您今日的提醒：\n\n";
                    }
                    num++;
                    notices += num + " ：" + reader["title"].ToString() + "\t开始时间：" + time + "\n\n";
                }

                if (notices.Length > 0)
                {
                    MessageBox.Show(notices);
                }
            }
            catch (Exception err)
            {
                Console.WriteLine("{0}\n", err.Message);
            }
            
           
        }
    }
}
